var express = require('express');
var router = express.Router();
const os = require('os');
var moment = require('moment');
let { isArrayEmpty, urlf2z, FormatData, urlf2zList } = require('../util.js');
let { isAdminLogin, getUserList, getUserCount, GetUsersById, DeleteUserById, UpdateAdminById, getAdminCount, GetAdminList,
  GetAdminById, DeleteAdminById, addAdmin, getSwiperList, deleteSwiperById, uploadSwiperImg, updataSwiperImg, getSpeedCount, getSpeedList,
  getSpeedById, addSpeed, deleteSpeedById, updataSpeed, getOrderCount, getUserListWord, getOrderList, DeleteorderById,getOrderById
} = require('../mysql/index');
let { ROWNUMBER } = require('../config');

let upload = require('../util/multer/index')

router.post('/isAdminLogin', async (req, res, next) => {
  let { username, password, code } = req.body;
  // try {
  //   const sessionCaptcha = req.session.captcha.toLowerCase();
  //   if (sessionCaptcha != code) {
  //     return res.json({
  //       flog: 0,
  //       data: '验证码不正确'
  //     });
  //   }
  // } catch (error) {
  //   return res.json({
  //     flog: 0,
  //     data: '验证码不正确'
  //   });
  // }
  let data = await isAdminLogin({
    username,
    password
  });
  if (isArrayEmpty(data)) {
    jsonData = {
      code: 0,
      data: "账号或者密码错误"
    }
  } else {
    jsonData = {
      code: 1,
      data: {
        "access_token": username,
        "name": username,
        "userId": data[0].id
      }
    }
    req.session.AdminInfo = {
      username: username,
      userId: data[0].id,
      url: data[0].url
    }
  }
  return res.json(jsonData)
});

router.get('/adminInfo', async (req, res, next) => {
  if (!req.session.AdminInfo) {
    return res.json({
      code: 500,
      msg: "未登录"
    })
  }
  res.json(
    {
      "code": 200,
      "user": {
        "userId": req.session.AdminInfo.userId,
        "username": req.session.AdminInfo.username,
        "nickName": req.session.AdminInfo.username,
        "url": req.session.AdminInfo.url,
        "type": req.session.AdminInfo.type
      }
    }
  )
});

router.get('/getUserList', async (req, res, next) => {
  let { page, limit, userId, userName, userSex } = req.query;
  let count = await getUserCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getUserList(num, limit, {
    userId, userName, userSex
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetUsersById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetUsersById(id);
  res.json({
    code: 1,
    data
  })
})

router.get('/DeleteUserById', async (req, res, next) => {
  let id = req.query.userId;
  let data = await DeleteUserById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminPassById', async (req, res, next) => {
  let { oldPsw, newPsw } = req.body;
  let id = req.session.AdminInfo.userId;
  let username = req.session.AdminInfo.username;
  let admin = await isAdminLogin({
    username,
    password: oldPsw
  });
  if (admin.length) {
    await UpdateAdminById(id, {
      password: newPsw
    })
    return res.json({
      code: 200,
      msg: "修改密码成功"
    })
  } else {
    return res.json({
      code: 500,
      msg: "旧密码错误"
    })
  }
})

router.get('/GetAdminList', async (req, res, next) => {
  let { page, limit, id, name } = req.query;
  let count = await getAdminCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await GetAdminList(num, limit, {
    id, name
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetAdminById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetAdminById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminById', upload.single('url'), async (req, res, next) => {
  let { id, name, password, sex, url } = req.body;
  console.log(req.file)
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await UpdateAdminById(id, { name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.post('/DeleteAdminById', async (req, res, next) => {
  let { id } = req.body;
  await DeleteAdminById(id);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/addAdmin', upload.single('url'), async (req, res, next) => {
  let { name, password, sex, url } = req.body;
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await addAdmin({ name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.post('/uploadSwiperImg', upload.single('file'), async (req, res, next) => {
  let url = `${req.protocol}://${req.headers.host}/${req.file.path}`;
  url = urlf2z(url)
  let data;
  if (req.body.swiperId) {
    data = await updataSwiperImg(req.body.swiperId, {
      swiperurl: url
    })
  } else {
    data = await uploadSwiperImg({
      swiperurl: url
    })
    await updataSwiperImg(data.insertId, {
      swiperIndex: data.insertId
    })
  }
  res.json({
    code: 1,
    url: url,
    swiperId: data.insertId
  })
})

router.get('/getSwiperList', async (req, res, next) => {
  let data = await getSwiperList();
  res.json({
    code: 1,
    data
  })
})

router.post('/deleteSwiperById', async (req, res, next) => {
  let { swiperId } = req.body;
  await deleteSwiperById(swiperId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/updataSwiperWz', async (req, res, next) => {
  let { swiperId, toswiperId } = req.body
  let arr = []
  let swiperIndex = await getSwiperIdByIndex(swiperId)
  let toswiperIndex = await getSwiperIdByIndex(toswiperId)
  arr.push({
    swiperId: swiperId,
    swiperIndex: toswiperIndex
  }, {
    swiperId: toswiperId,
    swiperIndex: swiperIndex
  })
  await updataSwiperWz(arr)
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getSpeedList', async (req, res, next) => {
  let { page, limit, speedId } = req.query;
  let count = await getSpeedCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: []
    });
  }
  var num = (page - 1) * limit;
  let data = await getSpeedList(num, limit, {
    speedId
  });
  res.json({
    code: 0,
    data: FormatData(data.data, {
      speedSeat: 'json',
      speedTime: 'hm',
      speedDate: "time"
    }),
    count: data.count
  })
})

router.get('/getSpeedById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await getSpeedById(editNo);
  res.json({
    code: 1,
    data: FormatData(data, {
      speedSeat: 'json',
      speedTime: 'hm',
      speedDate: "time"
    })
  })
})

router.post('/addSpeed', async (req, res, next) => {
  let { speedDate, speedMon, speedRow, speedSection, speedTime, startRegion, endRegion } = req.body;
  let speedPollall = 0, speedPolleave = 0, speedSeat = []
  for (let section = 0; section < Number(speedSection); section++) {
    let sectionList = []
    for (let row = 0; row < Number(speedRow); row++) {
      let rowList = []
      for (let i = 0; i < ROWNUMBER; i++) {
        speedPollall++
        rowList.push(0)
      }
      sectionList.push(rowList)
    }
    speedSeat.push(sectionList)
  }
  speedPolleave = speedPollall
  await addSpeed({
    speedDate, speedMon, speedRow, speedSection, speedTime, startRegion, endRegion, speedPolleave, speedPollall, speedSeat: JSON.stringify(speedSeat)
  })
  res.json({
    code: 1,
    data: "添加成功"
  })
})

router.post('/deleteSpeedById', async (req, res, next) => {
  let { speedId } = req.body
  await deleteSpeedById(speedId)
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/updataSpeed', async (req, res, next) => {
  let { speedId, speedDate, speedMon, speedRow, speedSection, speedTime, startRegion, endRegion } = req.body;
  let speedPollall = 0, speedPolleave = 0, speedSeat = []
  for (let section = 0; section < Number(speedSection); section++) {
    let sectionList = []
    for (let row = 0; row < Number(speedRow); row++) {
      let rowList = []
      for (let i = 0; i < ROWNUMBER; i++) {
        speedPollall++
        rowList.push(0)
      }
      sectionList.push(rowList)
    }
    speedSeat.push(sectionList)
  }
  speedPolleave = speedPollall
  await updataSpeed(speedId, {
    speedDate, speedMon, speedRow, speedSection, speedTime, startRegion, endRegion, speedPolleave, speedPollall, speedSeat: JSON.stringify(speedSeat)
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getIndexCount', async (req, res, next) => {
  let adminNum = await getAdminCount();
  let speedNum = await getSpeedCount();
  let orderNum = await getOrderCount();
  let userNum = await getUserCount();
  res.json({
    code: 1,
    adminNum, speedNum, orderNum, userNum
  })
})

router.get('/getuserNumTable', async (req, res, next) => {
  let DayList = [];
  for (var i = 1; i <= 7; i++) {
    DayList.push(moment().isoWeekday(i))
  }
  let { count, data } = await getUserListWord();
  let userNum = []
  DayList.forEach(dayItem => {
    let sunNum = 0;
    data.forEach(item => {
      if (dayItem.isSame(item.userTime, 'day')) {
        sunNum++;
      }
    })
    userNum.push(sunNum)
  })

  res.json({
    code: 1,
    userNum: userNum,
    count: count
  })

});

router.get('/getOrderList', async (req, res, next) => {
  let { page, limit, orderId } = req.query;
  let count = await getOrderCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: []
    });
  }
  var num = (page - 1) * limit;
  let data = await getOrderList(num, limit, {
    orderId
  });
  res.json({
    code: 0,
    data: FormatData(data.data, {
      passenger: 'json',
      seatList: 'json',
      speedSeat: 'json',
      speedTime: 'hm',
      speedDate: "time"
    }),
    count: data.count
  })
})

router.post('/DeleteorderById', async (req, res, next) => {
  let { orderId } = req.body
  await DeleteorderById(orderId)
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/getOrderById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await getOrderById(editNo);
  res.json({
    code: 1,
    data: FormatData(data, {
      passenger: 'json',
      seatList: 'json',
      speedSeat: 'json',
      speedTime: 'hm',
      speedDate: "time"
    })
  })
})

router.get('/getCpuTable', async (req, res, next) => {
  var freeMem = os.freemem() / 1024 / 1024 / 1024;
  var totalMem = os.totalmem() / 1024 / 1024 / 1024;
  res.json({
    code: 1,
    CpuNum: ((freeMem) / totalMem * 100.0).toFixed(2)
  })
})


module.exports = router;